package com.util;

import io.netty.buffer.ByteBuf;

/**
 * Self defined protocol utilize class
 */
public class ProtocolUtil {
    public static final byte KEEP_ALIVE =  (byte)0xF0; // 心跳帧
    public static final byte ACK = (byte)0xF1; // 应答帧
    public static final byte PKT_RQ = (byte)0xF2; // 分包请求帧
    public static final byte PKT = (byte)0xF3; // 分包数据帧
    public static final byte UPGRADE = (byte)0x20; // 远程升级帧
    public static final byte UPGRADE_RESULT = (byte)0x25; // 升级结果帧
    public static final byte ERROR_CONNECTION = (byte)0x28; // 读取错误连接地址（28H）
    public static final byte HOST_SERVER_FRAME_TYPE_OFFSET = 3; // 主机至服务器帧类型偏移量
    public static final byte HOST_SERVER_DATA_BEGIN_OFFSET = 10; // 数据域的地址偏移量
    public static final byte HOST_SERVER_FRAME_HEADER_TAIL_LENGTH = 11; // 协议头尾的长度和
    public static final byte UPGRADE_UNPACK_FRAME_BYTE_LENGTH  = 2; // 升级数据包的包序号字节数
    public static final int SLAVE_NUMBER = 24; // 从机个数



    private static final int MIN_FRAME_LENGHT = 11;
    private static final int GPRSID_FRAME_OFFSET = 4;
    private static final int GPRSID_FRAME_LENGTH = 6;




    public static String getGprsId(ByteBuf frame){
        if (frame.readableBytes() < MIN_FRAME_LENGHT)
            return null;
        else{
            byte[] idFrame = new byte[GPRSID_FRAME_LENGTH];
            frame.getBytes(GPRSID_FRAME_OFFSET, idFrame, 0, GPRSID_FRAME_LENGTH);
            return getGprsId(idFrame);
        }
    }

    private static String getGprsId(byte[] frame){
        if (frame.length != 6) throw new IllegalArgumentException("GprsId Frame Length error, need 6 bytes not " + frame.length);
        StringBuilder sb = new StringBuilder();
        sb.append((char)frame[0]);
        sb.append((char)frame[1]);
        sb.append((char)frame[2]);
        long index = MyUtil.getUInt32(new byte[]{frame[5], frame[4], frame[3], 0x00});
        sb.append(MyUtil.padLeft(index, 6, '0'));
        return sb.toString();
    }
}
